package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author GRS
 * @since 2024/4/27 下午7:41
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController
{
    @Resource
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart)
    {
        // 设置用户ID，指定当前是哪个用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);

        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper
            .eq(ShoppingCart::getUserId, userId)
            .eq(dishId != null, ShoppingCart::getDishId, dishId)
            .eq(dishId == null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart one = shoppingCartService.getOne(wrapper);

        // 查询当前菜品或者套餐是否在购物车中
        if (one != null)
        {
            // 如果已经存在，就在原来数量基础上加 1
            one.setNumber(one.getNumber() + 1);
            shoppingCartService.updateById(one);
        }
        else
        {
            // 如果不存在，则添加到购物车，数量默认是 1
            shoppingCart.setNumber(1);
            SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            shoppingCart.setCreateTime(SDF.format(System.currentTimeMillis()));
            shoppingCartService.save(shoppingCart);
            one = shoppingCart;
        }
        return R.success(one);
    }

    /**
     * 查看购物车
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list()
    {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper
            .eq(ShoppingCart::getUserId, userId)
            .orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        return R.success(list);
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clean")
    public R<String> clean()
    {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);

        shoppingCartService.remove(wrapper);
        return R.success("清空购物车成功");
    }
}